package tp1;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.MulticastSocket;

// Thread du client pour lancer la communication UDP

public class ClientUDP extends Thread{

	Utilisateur usr;
	Groupe groupe;
	MulticastSocket multSocket;
	boolean continuer = true;
	String dernierMsg = "";
    Client clientParent = Client.getInstance();
    
	public ClientUDP(Groupe g, MulticastSocket s, Utilisateur u)
	{
		this.usr = u;
		this.groupe = g;
		this.multSocket = s;
	}
	public void run(){
		
		try {
			multSocket = new MulticastSocket(groupe.port);
			multSocket.joinGroup(groupe.adresseMulticast);
			byte[] receiveData = null;
			while (continuer) {
			receiveData = new byte[1024];
			DatagramPacket receivePacket = new
			DatagramPacket(receiveData, receiveData.length);
			multSocket.receive(receivePacket);
			String sentence = new String(receivePacket.getData());
			clientParent.debug("[ClientUDP] Reçu msg multicast "+ sentence);
			if(sentence.length()> 2 ) {
                String head = sentence.substring(0, 3);
                String nMsg = sentence.substring(3, 5);
                String identifiant = sentence.substring(5, 11);
                String text = sentence.substring(11);
                if(!identifiant.equalsIgnoreCase(clientParent.usrCourant.getIdentifiant())) // si le message vient de l'utilisateur même, ne pas l'afficher
                    System.out.println("\n"+clientParent.ANSI_GREEN + "[Groupe " + groupe.getNom() + " | " + identifiant + "#"+nMsg+"] " + clientParent.ANSI_RESET + text);
                if (head.equalsIgnoreCase("HLO")) {
                    InetAddress source = receivePacket.getAddress();
                    int port = receivePacket.getPort();
                    byte[] messageEnvoyer = new byte[1024];
                    DatagramSocket sendSocket = new DatagramSocket();
                    if (!dernierMsg.substring(0, 3).equalsIgnoreCase("HLO")) {
                        messageEnvoyer = dernierMsg.getBytes();
                        DatagramPacket sendPacket = new
                                DatagramPacket(messageEnvoyer, messageEnvoyer.length, source, port);
                        sendSocket.send(sendPacket);
                        sendSocket.close();
                    }
                }
            }
		
			}
			} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			}

        }
	public void arreter(){

        continuer = false;
        try {
            multSocket.leaveGroup(groupe.adresseMulticast);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
	
	public void setDernierMsg(String s){
		this.dernierMsg = s;
	}
}
